package com.fs.flow.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import lombok.Getter;
import lombok.Setter;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fs.base.pojo.ModleField;
import com.fs.base.repository.SqlRepository;
import com.fs.base.utils.ApplicationUtils;
import com.fs.base.utils.ModleTools;
import com.fs.base.vo.JsonResponse;
import com.fs.flow.pojo.JForm;
import com.fs.flow.pojo.JFormDesign;
import com.fs.flow.pojo.ProcessTaskConfig;
import com.fs.flow.repository.JFormDesignRepository;
import com.fs.flow.repository.JFormRepository;
import com.fs.flow.repository.ProcessTaskConfigRepository;

/**
 * 表单处理器
 *
 */
@Controller
@RequestMapping("/console/jForm/rewrite")
public class JFormController {
	@Getter @Setter @Value("${flow.sql.t1}")
    private String sqlTemplate1;
	
	@Getter @Setter @Value("${flow.sql.t2}")
    private String sqlTemplate2;
	
	@Getter @Setter @Value("${flow.sql.t3}")
    private String sqlTemplate3;
	
	@Autowired private SqlRepository sqlRepository;
	
	private static final Logger log = Logger.getLogger(JFormController.class); 
	@Autowired private JFormRepository jFormRepository;
	@Autowired private JFormDesignRepository jFormDesignRepository;
	@Autowired private ProcessTaskConfigRepository processTaskConfigRepository;
	
	
	@GetMapping("design")
	public String design(String formId,HttpServletRequest request){
		JForm jForm = jFormRepository.findOne(formId);
		//System.out.println(jForm);
		request.setAttribute("jForm", jForm);
		return "/console/jForm/design";
	}
	
	
	@GetMapping("dbDesign")
	public String dbDesign(String formId,HttpServletRequest request){
		//JFormDesign design = jFormDesignRepository.findByFormId(formId);
		//request.setAttribute("design", design);
		return "/console/jForm/db_design";
	}
	
	/**
	 * 设计预览
	 * @param tableName
	 * @param request
	 * @return
	 */
	@RequestMapping("review")
	public String review(String editorContent,HttpServletRequest request){
		if(StringUtils.isNotBlank(editorContent)){
			JSONObject table = JSON.parseObject(editorContent);
			request.setAttribute("editorContent", table.get("template"));
		}else{
			String formId = request.getParameter("formId");
			
			JFormDesign design = jFormDesignRepository.findByFormId(formId);
			
			if(design!=null){
				request.setAttribute("editorContent", design.getParse());
			}else{
				request.setAttribute("editorContent", "<center><p>此表单未设计</p></center>");
			}
			
			JForm jform = jFormRepository.findOne(formId);
			request.setAttribute("jform", jform);
		}
		return "/console/jForm/review";
	}
	
	
	@ResponseBody
	@RequestMapping("/getFormDataGrid")
	public JSONObject getFormData(String formId) {
		JSONObject json = new JSONObject();
		try {
			JSONArray data = new JSONArray();
			JFormDesign design = jFormDesignRepository.findByFormId(formId);
			if(design!=null && StringUtils.isNotBlank(design.getData())){
				data = JSON.parseArray(design.getData());
			}
			json.put("rows", data);
			json.put("total", data.size());
		} catch (Exception e) {
			json.put("rows", new JSONArray());
			json.put("total", 0);
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return json;
	}
	
	
	@ResponseBody
	@RequestMapping("/getJformByTableName")
	public JsonResponse getJformByTableName(String tableName) {
		try {
			if(StringUtils.isNotBlank(tableName)){
				JForm form = jFormRepository.findByfTableName(tableName);
				return JsonResponse.success(form);
			}else{
				return JsonResponse.error("未指定表名称！");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return JsonResponse.error(e.getMessage());
		}
	}
	
	
	@ResponseBody
	@RequestMapping("/getDbGrid")
	public JSONObject getDbGrid(String formId) {
		JSONObject json = new JSONObject();
		try {
			JSONArray data = new JSONArray();
			JForm jForm = jFormRepository.findOne(formId);
			if(jForm==null){
				formId = formId.replace("table:'", "").replace("'", "");
				jForm = jFormRepository.findByfTableName(formId);
			}
			if(jForm!=null){
				if(StringUtils.isNotBlank(jForm.getDbConfig())){
					json = JSON.parseObject(jForm.getDbConfig());
					json.put("fName", jForm.getFName());
					json.put("fTableName", jForm.getFTableName());
					/*JSONArray rows = json.getJSONArray("rows");
					for(int i=0,len=rows.size(); i<len; i++){
						JSONObject item = rows.getJSONObject(i);
						//System.out.println(item.get("fieldPlug"));
						//System.out.println(item);
						if(item.containsKey("fieldPlug") && "关联子表".equals(item.getString("fieldPlug")) && item.containsKey("fieldRequired") ){
							String fieldRequired = item.getString("fieldRequired");
							String[]fields = fieldRequired.split(",");
							for(String f: fields){
								if(f.startsWith("table:")){
									String tableName = f.replace("table:", "").replace("'", "");
									JForm itemTable = jFormRepository.findByfTableName(tableName);
									if(itemTable!=null){
										json.put(tableName, JSON.parseObject(itemTable.getDbConfig()));
									}
								}
							}
						}
					}*/
					return json ;
				}else{
					String sql = "select column_name,data_type from information_schema.columns  where table_name='#table_name#' ";
					sql = sql.replace("#table_name#", jForm.getFTableName());
					List<String[]> items = sqlRepository.list(sql, null, null);
					for(Object item: items){
						JSONObject itemJson = new JSONObject();
						Object[] arrs = (Object[])item;
						itemJson.put("fieldName", arrs[0]);
						itemJson.put("fieldType", arrs[1]);
						data.add(itemJson);
					}
				}
				json.put("fName", jForm.getFName());
				json.put("fTableName", jForm.getFTableName());
			}
			json.put("rows", data);
			json.put("total", data.size());
		} catch (Exception e) {
			json.put("rows", new JSONArray());
			json.put("total", 0);
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return json;
	}
	
	/**
	 * 流程节点表单配置
	 * @param processKey
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getTaskFormConfig")
	public JSONObject getTaskFormConfig(String processKey,String taskId) {
		JSONObject json = new JSONObject();
		try {
			String formJson = null;
			ProcessTaskConfig config = processTaskConfigRepository.findByProcessKeyAndTaskId(processKey, taskId);
			if(config!=null &&  StringUtils.isNotBlank(config.getFormJson())){
				formJson = config.getFormJson();
				if(StringUtils.isNotBlank(formJson)){
					json = JSON.parseObject(formJson);
				}
			}else{
				List<ModleField> list = ModleTools.modleField(processKey);
				if(list==null || list.size()==0){
					list = new ArrayList<ModleField>();
				}
				formJson = JSON.toJSONString(list);
				JSONArray rows = JSON.parseArray(formJson);
				json.put("rows", rows);
				json.put("total", rows.size());
			}
			/*if(StringUtils.isNotBlank(formJson)){
				System.out.println(formJson);
				json = JSON.parseObject(formJson);
			}else{
				json.put("rows", new JSONArray());
				json.put("total", 0);
			}*/
		} catch (Exception e) {
			json.put("rows", new JSONArray());
			json.put("total", 0);
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return json;
	}
	
	
	@ResponseBody
	@RequestMapping("/tableConfig")
	public JsonResponse tableConfig(String formId,String tableConfig) {
		try {
			if(StringUtils.isNotBlank(formId) && StringUtils.isNotBlank(tableConfig)){
				JForm form = jFormRepository.findOne(formId);
				form.setDbConfig(tableConfig);
				jFormRepository.save(form);
				return JsonResponse.success();
			}else{
				return JsonResponse.error("参数不完整！");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return JsonResponse.error(e.getMessage());
		}
	}
	
	
	/**
	 * 
	 * @param tableName 表单表名
	 * @param jFormJson 设计json
	 * @param type	类型 设计或暂存 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/designSave")
	public JsonResponse designSave(String formId,String formConfig) {
		try {
			JForm form = jFormRepository.findOne(formId);
			form.setFormConfig(formConfig);
			
			form.setFStatus("已设计");
			jFormRepository.save(form);
			
			return JsonResponse.success();
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return JsonResponse.error(e.getMessage());
		}
	}
	
	@ResponseBody
	@RequestMapping("/submit")
	public JsonResponse submit(HttpServletRequest request) {
		try {
			Map<String, Object> map = ApplicationUtils.getRequestDatas();
			for(String key: map.keySet()){
				System.out.println("key:"+ key + " value:"+ map.get(key));
			}
			return JsonResponse.success();
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return JsonResponse.error(e.getMessage());
		}
	}
	
	
	@Transactional
	@ResponseBody
	@RequestMapping("/newAdd")
	public JsonResponse newAdd(JForm jForm) {
		try {
			Map<String, String> map = new HashMap<String, String>();
			map.put("t1", sqlTemplate1);
			map.put("t2", sqlTemplate2);
			map.put("t3", sqlTemplate3);
			
			jFormRepository.save(jForm);
			if(StringUtils.isNotBlank(jForm.getFSqlTemplate()) && StringUtils.isNotBlank(jForm.getFTableName())){
				String sql = map.get(jForm.getFSqlTemplate()).replace("#tableName#", jForm.getFTableName());
				sqlRepository.excute(sql);
			}
			return JsonResponse.success();
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return JsonResponse.error(e.getMessage());
		}
	}
	
}
